package com.java.util.zip;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * java 压缩类使用 Deflater 和 Inflater
 * 
 * @author Ben
 *
 * @date 2018年3月16日
 */
public class ZipTest {

    public static String percnet(double d, double e) {
        double p = d / e;
        DecimalFormat nf = (DecimalFormat) NumberFormat.getPercentInstance();
        nf.applyPattern("00%"); // 00表示小数点2位
        nf.setMaximumFractionDigits(2); // 2表示精确到小数点后2位
        return nf.format(p);
    }

    public static void main(String[] args) {
        String inputStr = "hello world.fdsaadfsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        try {
            byte[] outputStr = inputStr.getBytes("UTF-8");

            byte[] output = new byte[100];
            Deflater compress = new Deflater();
            compress.setInput(outputStr);
            compress.finish();
            int compressDataLength = compress.deflate(output);
            System.out.println(compressDataLength);

            // decompress
            Inflater decompress = new Inflater();
            byte[] input = new byte[100];
            decompress.setInput(output, 0, compressDataLength);
            int resultLength = decompress.inflate(input);
            System.out.println(resultLength);
            decompress.end();

            if (resultLength < compressDataLength) {
                System.out.println("负压缩比");
            } else {
                System.out.println(percnet((double) compressDataLength, (double) resultLength));
            }
            System.out.println(new String(input, 0, resultLength, "UTF-8"));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
